package gro.ecorrdata.edata.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import gro.ecorrdata.edata.annotation.NoneAuth;
import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.MyUtil;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/permission")
public class PerimissionController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @NoneAuth
    // @CrossOrigin
    @RequestMapping("/getmenu")
    public BaseResponse<List<Map<String, Object>>> getMenu(HttpServletRequest request){
        String authStr = request.getHeader("authStr");
        String[] modelArr = authStr.split("-");
        int userId = Integer.parseInt(modelArr[0]);
        String sqlRole = "select role_id from admin_user where id=?";
        Map<String, Object> rMap = jdbcTemplate.queryForMap(sqlRole, userId);
        int role_id = Integer.parseInt(rMap.get("role_id").toString());

        String sql = "";
        if (role_id==1) {
          sql = "select id,pid,name,method from permission where status=1 and menu=1";
            // System.out.println(sql);
        } else {
            String sqlPer = "select permission from admin_role where id=?";
            Map<String, Object> pMap = jdbcTemplate.queryForMap(sqlPer, role_id);
            String pers = (String) pMap.get("permission");
            sql = "select `id`,`pid`,`name`,`method` from `permission` where `status`=1 and `menu`=1 and `id` in("+ pers +")";
            // System.out.println(pers);
            // System.out.println(sql);
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> result = MyUtil.makeClassListTree(list, "0");

        return new BaseResponse<>(true, "查询成功", result);
    }

    
    @PostMapping("/list")
    public BaseResponse<List<Map<String, Object>>> getList(){
        return new BaseResponse<>(true, "查询成功", getListTree());
    }

    public List<Map<String, Object>> getListTree(){
        String sql = "SELECT id,pid,name,method,note FROM permission as ar where status=1 and isdel=0";
        try {
            // System.out.println(sql);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> result = MyUtil.makeClassListTree(list, "0");
            return result;
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/getpermission")
    public BaseResponse<Map<String, Object>> getPermission(Integer id) {
        String sql = "select id,pid,name,method,note from permission where id=?";
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);
            List<Map<String, Object>> pList = getListTree();
            result.put("permission", map);
            result.put("pList", pList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResponse<>(true, "查询成功", result);
    }

    @PostMapping("/update")
    public BaseResponse<Object> update(HttpServletRequest request) {
        boolean result = false;
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        if (name==null || name== "") {
            return new BaseResponse<>(false, "权限名不能为空", null);
        }
        Integer pid = (request.getParameter("pid")==null || request.getParameter("pid")=="") ? 0 : Integer.parseInt(request.getParameter("pid"));
        String method = (request.getParameter("method")==null || request.getParameter("method")=="") ? "" : request.getParameter("method");
        String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
        Long ctime = (Long) (System.currentTimeMillis()/1000);
        if (id == null || id=="") {  // 添加
            
            String sql = "INSERT INTO permission(pid, name, method, create_time, note) VALUES(?,?,?,?,?)";
            
            int itemp = jdbcTemplate.update(sql,new Object[]{pid, name, method, ctime, note});

            if (itemp > 0) {
                result =true;
            }   
        } else {   // 修改
            String sql = "UPDATE permission SET pid=?, name=?, method=?, note=?  where `id`=? ";

            int itemp = jdbcTemplate.update(sql, new Object[]{pid, name, method, note, id});

            if (itemp > 0) {
                result =true;
            }   
        }

        if (result==true) {
            System.out.println("Ok!");
            return new BaseResponse<>(true, "操作成功!", null);
        } else {
            System.out.println("Error!");
            return new BaseResponse<>(false, "操作失败!", null);
        }
    }

    @PostMapping("/delete")
    public BaseResponse<Object> delete(Integer id) {
        boolean result = false;
        if (id == null) {
            return new BaseResponse<>(false, "找不到要删除的数据", null);
        }

        String sql = "SELECT count(*) as counts FROM permission WHERE isdel=0 and pid=?";

        Map<String, Object> res = jdbcTemplate.queryForMap(sql, id);

        Long count = (Long) res.get("counts");
        // System.out.println(count);

        if (count!=0) {
            return new BaseResponse<>(false, "子权限不为空不可删除", null);
        }

        String sql2 = "UPDATE permission SET `isdel`=1 where `id`=?";
        // System.out.println(sql);
        // System.out.println(id);
        try {
            jdbcTemplate.update(sql2, id);
            
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return new BaseResponse<>(result, "操作完成", null);
    }
}
